"""
脚本扫描账号管理器
"""
from typing import Optional, List, Dict, Any
from sqlalchemy import desc, or_
from .models import ScriptScanAccount
from .sqlalchemy_database import SQLAlchemyDatabaseManager

class ScriptScanAccountManager:
    def __init__(self):
        """
        初始化脚本扫描账号管理器
        """
        self.db = SQLAlchemyDatabaseManager()

    def get_by_id(self, record_id: int) -> Optional[Dict[str, Any]]:
        """
        根据ID获取记录
        :param record_id: 记录ID
        :return: 记录信息字典或None
        """
        record = self.db.get_by_id(ScriptScanAccount, record_id)
        return self._convert_model_to_dict(record) if record else None

    def get_by_script_id(self, script_id: int) -> List[Dict[str, Any]]:
        """
        根据脚本ID获取所有相关记录
        :param script_id: 脚本ID
        :return: 记录列表
        """
        records = self.db.query(ScriptScanAccount).filter(ScriptScanAccount.script_id == script_id).all()
        return [self._convert_model_to_dict(record) for record in records]

    def get_by_scan_account_id(self, scan_account_id: int) -> List[Dict[str, Any]]:
        """
        根据扫描账号ID获取所有相关记录
        :param scan_account_id: 扫描账号ID
        :return: 记录列表
        """
        records = self.db.query(ScriptScanAccount).filter(ScriptScanAccount.scan_account_id == scan_account_id).all()
        return [self._convert_model_to_dict(record) for record in records]

    def get_all(self, limit: int = None, offset: int = None) -> List[Dict[str, Any]]:
        """
        获取所有记录
        :param limit: 限制返回数量
        :param offset: 偏移量（用于分页）
        :return: 记录列表
        """
        query = self.db.query(ScriptScanAccount)
        
        if limit is not None and offset is not None:
            query = query.limit(limit).offset(offset)
            
        records = query.all()
        return [self._convert_model_to_dict(record) for record in records]

    def add(self, script_id: int, scan_account_id: int) -> int:
        """
        添加新记录
        :param script_id: 脚本ID
        :param scan_account_id: 扫描账号ID
        :return: 新记录的ID
        """
        try:
            print(f"添加扫描账号关联，script_id={script_id}, scan_account_id={scan_account_id}")
            record = ScriptScanAccount(
                script_id=script_id,
                scan_account_id=scan_account_id
            )
            print(f"创建关联对象: {record.__dict__}")
            record_id = self.db.add(record)
            print(f"保存关联成功，ID: {record_id}")
            return record_id
        except Exception as e:
            import traceback
            print(f"添加扫描账号关联失败: {str(e)}\n{traceback.format_exc()}")
            raise

    def delete(self, record_id: int) -> bool:
        """
        删除记录
        :param record_id: 记录ID
        :return: 是否成功
        """
        record = self.db.get_by_id(ScriptScanAccount, record_id)
        if not record:
            return False
            
        self.db.delete_obj(record)
        return True

    def delete_by_script_id(self, script_id: int) -> bool:
        """
        删除指定脚本的所有记录
        :param script_id: 脚本ID
        :return: 是否成功
        """
        try:
            print(f"删除脚本扫货账号关联，script_id={script_id}")
            session = self.db.get_session()
            try:
                session.query(ScriptScanAccount).filter(
                    ScriptScanAccount.script_id == script_id
                ).delete(synchronize_session=False)
                session.commit()
                print(f"删除脚本扫货账号关联成功")
                return True
            except Exception as e:
                session.rollback()
                raise
            finally:
                session.close()
        except Exception as e:
            import traceback
            print(f"删除脚本扫货账号关联失败: {str(e)}\n{traceback.format_exc()}")
            raise

    def delete_by_scan_account_id(self, scan_account_id: int) -> bool:
        """
        删除指定扫描账号的所有记录
        :param scan_account_id: 扫描账号ID
        :return: 是否成功
        """
        self.db.query(ScriptScanAccount).filter(ScriptScanAccount.scan_account_id == scan_account_id).delete()
        return True

    def get_scan_accounts_by_script_id(self, script_id: int) -> List[Dict[str, Any]]:
        """
        获取脚本关联的扫货账号
        :param script_id: 脚本ID
        :return: 扫货账号列表
        """
        try:
            print(f"获取脚本扫货账号，script_id={script_id}")
            session = self.db.get_session()
            try:
                # 联表查询扫货账号信息
                from .models import ScanAccount
                results = session.query(ScanAccount).join(
                    ScriptScanAccount, ScriptScanAccount.scan_account_id == ScanAccount.id
                ).filter(
                    ScriptScanAccount.script_id == script_id,
                    ScanAccount.status == 1,
                    ScanAccount.alive == 1
                ).all()
                
                accounts = []
                for account in results:
                    account_dict = {
                        'id': account.id,
                        'name': account.name,
                        'uu_token': account.uu_token,
                        'device_id': account.device_id,
                        'alive': account.alive,
                        'status': account.status,
                        'locked': account.locked,
                        'safe_verify': account.safe_verify,
                        'uu_user_id': account.uu_user_id,
                        'avatar': account.avatar,
                        'nickname': account.nickname,
                        'steam_id': account.steam_id,
                        'create_at': account.create_at,
                        'update_at': account.update_at,
                        'uk': account.uk
                    }
                    accounts.append(account_dict)
                    
                print(f"获取到{len(accounts)}个扫货账号")
                return accounts
            finally:
                session.close()
        except Exception as e:
            import traceback
            print(f"获取脚本扫货账号失败: {str(e)}\n{traceback.format_exc()}")
            raise

    def _convert_model_to_dict(self, model: ScriptScanAccount) -> Dict[str, Any]:
        """
        将模型对象转换为字典
        :param model: 模型对象
        :return: 字典
        """
        if not model:
            return None
            
        return {
            'id': model.id,
            'script_id': model.script_id,
            'scan_account_id': model.scan_account_id
        }
